<?php
namespace Company\Controller;
use Think\Controller;
class RegController extends Controller {
	public function _initialize()
    {
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		//数据库连接基础配置-end
    }
    public function login(){
        $this->display();
    }
	//总后台管理员登录
	public function admin_manage(){
			session('company',null);
			$admin=session('admin.admin');
			$admin_info=session('admin.admin_info');
			if(!empty($admin) and !empty($admin_info)){
				$erp_id=I('erp_id');
				$user=M('User');
				$result=$user->where(array('id'=>$erp_id))->find();
				if(!empty($result)){
					$result['db']=C('DB_PREFIX_T').$result['username'];
					$result['type']=1;
					$result['company_id']=$result['id'];
					session('company',$result);
					$this->ajaxReturn(array('status'=>1,'message'=>"成功"));
				}else{
					$this->ajaxReturn(array('status'=>0,'message'=>"没有此用户数据"));
				}
			}else{
				$this->ajaxReturn(array('status'=>0,'message'=>"没有权限"));
			}
	}
    public function verify(){
		ob_clean();
        $config =    array(
            'fontSize'    =>    12,
            'length'      =>    3,
            'useNoise'    =>    false,
            'bg'=>array(229,229,229),
        );
        $Verify =     new \Think\Verify($config);
        $Verify->entry();
    }
    public function verify_check($code,$id){
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }
    public function loginCheck($username,$password,$type,$company,$verify){
        if($type!=0 && $type!=1){
            alert(0,'操作有误');
        }
        if(!$this->verify_check($verify)){
            alert(0,'验证码错误');
        }
        if($username==''){
            alert(0,'用户名不能为空');
        }
        // if(!mobile($username) && $type==1){
            // alert(0,'手机号码错误');
        // }
        if($password==''){
            alert(0,'密码不能为空');
        }
        if($type==0 && $company==''){
            alert(0,'企业名称不能为空');
        }
        $where['username']=$username;
        if($type==1){//主账号
            $result=M('user')->where($where)->find();
			if(empty($result)){
				$result=M('user')->where(array('nick_name'=>$username))->find();
				if(empty($result)){
					alert(0,"没有此账号");
				}
			}
			if($result['status']==0){
				alert(0,'正在审核！');
			}
			if($result['status']==2){
				alert(0,'未通过审核！');
			}
            if(count($result)==0){
                alert(0,'用户名不存在');
            }
            if($result['password']==md5($password. $result['salt'])){
                $result['db']=C('DB_PREFIX_T').$result['username'];
                $result['type']=1;
                $result['company_id']=$result['id'];
                session('company',$result);
				// $book=A('Book');
				// $book->syn_book(1);//账册同步
                alert(1,'登录成功');
            }else{
                alert(0,'密码错误');
            }
        }else{///次账号
            $user=M('user')->where(array('company'=>$company))->find();
			$user['db']=C('DB_PREFIX_T').$user['username'];
            $m_username=$user['username'];
            if($m_username===null){
                alert(0,'公司名称不存在');
            }
            $db_name=C('DB_PREFIX_T').$m_username;
            
			C('erp_dbname',$db_name);
			C('db_config.DB_NAME',C('erp_dbname'));
			$m = M('role',C('DB_PREFIX_T'), C('db_config'));
			
            $result=$m->where($where)->find();
			if(empty($result)){
				$result=$m->where(array('nick_name'=>$username))->find();
				if(empty($result)){
					alert(0,"没有此账号");
				}
			}
            if(count($result)==0){
                alert(0,'用户名不存在');
            }
            if($result['password']==md5($password. $result['salt'])){
                $result['db']=C('DB_PREFIX_T').$m_username;
                // $result['type']=0;
                $result['company_id']=$user['id'];
				$user['type']=0;
                $result['company']=$user['company'];
                session('company',$user);//主账号
				session('company.childs',$result);//子账号
                $res=$m->where($where)->setInc("login_count");
				if(!$res){
					$m->where(array('nick_name'=>$username))->setInc("login_count");
				}
                $res=$m->where($where)->setField("last_login_date",date("Y-m-d H:i:s",time()));
				if(!$res){
					$res=$m->where(array('nick_name'=>$username))->setField("last_login_date",date("Y-m-d H:i:s",time()));
				}
				// $book=A('Book');
				// $book->syn_book(1);//账册同步
                alert(1,'登录成功');
            }else{
                alert(0,'密码错误');
            }
        }
    }
    public function register(){
		// dump(session());
        $this->display();
    }
    public function exits(){
        session('company',null);
        session('user_root',null);
        $this->redirect('Reg/login');
    }
    public function registerD($company,$username,$nick_name,$pwd,$pwd2,$name,$email){

        if($company==''){
            alert(0,'用户名不能为空');
        }
        if($username==''){
            alert(0,'用户名不能为空');
        }
		if(mobile($nick_name)){
            alert(0,'昵称不能为手机号');
        }
		if($nick_name==''){
            alert(0,'昵称不能为空');
        }
		if($nick_name==$username){
            alert(0,'昵称不能与用户名相同');
        }
        if($pwd==''){
            alert(0,'密码不能为空');
        }
        if($pwd2!=$pwd){
            alert(0,'两次密码不相同');
        }
        if($email==''){
            alert(0,'E-mail不能为空');
        }
        if($name==''){
            alert(0,'姓名不能为空');
        }
        if(!email($email)){
            alert(0,'邮箱地址错误');
        }
        if(!mobile($username)){
            alert(0,'手机号码错误');
        }
        if(M("user")->where("username='".$username."'")->count()>=1){
            alert(0,'用户名已经存在！');
        }
		if(M("user")->where("nick_name='".$username."'")->count()>=1){
            alert(0,'用户名已经存在！');
        }
		if(M("user")->where("username='".$nick_name."'")->count()>=1){
            alert(0,'昵称已经存在！');
        }
		if(M("user")->where("nick_name='".$nick_name."'")->count()>=1){
            alert(0,'昵称已经存在！');
        }
        if(M("user")->where("company='".$company."'")->count()>=1){
            alert(0,'公司名称已经存在！');
        }
        if(M("user")->where("email='".$email."'")->count()>=1){
            alert(0,'电子邮箱已经存在！');
        }
		// $member=I('member');
        $data['salt']=rand(10000,99999);
        $data['username']=$username;
		$data['nick_name']=$nick_name;
		// $data['member']=$member;
        $data['company']=$company;
        $data['password']=md5($pwd.$data['salt']);
        $data['name']=$name;
        $data['email']=$email;
		$data['status']=0;
		$data['warehouse_code']="T".rand(1000000,9999999);//虚拟仓仓库编码
        $result=M("user")->add($data);
        if($result){
            if($this->createDb(C('DB_PREFIX_T').$username)){
                alert(1,'注册成功');
            }else{
                alert(0,'注册失败，请重试');
            }
        }else{
            alert(0,'注册失败，请重试');
        }
    }
	//username数据库名称
    // public function createDb($username){	
        // $m=M();
        // $f=C('DB_PREFIX_T');
        // $db_name=array('arrival_order','bill','bill_cate','bind_list_bill','book','category','coin','config','contacts_company','cost','country','department','factory_rule','inbound_plan','inbound_plan_detail','level_rule','list','list_cost','list_product','massage','personnel','product','product_order','product_order_byproduct','product_order_detail','pushorder_salesman_cost','pushorder_salesman','pushordergoods_salesman','role','root','section','unit');
        // $m->execute("CREATE DATABASE ".$username);
        // foreach($db_name as $v){
            // $m->execute("CREATE TABLE ".$username.".".$f.$v." LIKE ".$f."main.".$f.$v);
            // if($v=='category' || $v=='root' || $v=='config'){
                // $m->execute("INSERT INTO ".$username.".".$f.$v." SELECT * FROM ".$f."main.".$f.$v);
            // }
        // }
		// $sql_interfaces="INSERT INTO ".$username.".".$f."interfaces SELECT * FROM ".$f."interfaces where warehouse_id=30";
        // return true;
    // }
	//创建数据库
	//$username 数据库名称
	public function createDb($username){

		//创建数据库 事务会自动提交
		$dbName=$username;//数据库名称 "tzwms_+手机号"		
		$Model = M();
		$sql_head="SELECT * FROM information_schema.SCHEMATA where SCHEMA_NAME='$dbName';";
		$ress = $Model->query($sql_head);
		if(!empty($ress)){
			alert(0,'数据库已存在');
		}
		$res2 = $Model->execute('create database ' . $dbName);

		if($res2 === false){
			alert(0,'生成数据失败！');
		}else{
			//使用读取写入方式导入
			require_once('./cloudAPP/Admin/Common/DBManage.class.php');
			$db = new \DBManage(C('DB_HOST'), C('DB_USER'), C('DB_PWD'), $dbName , 'utf8' );
			
			//输出缓存
			ob_start();
			//导入
			$db->restore('./data/erp.sql');//空数据
			$db->restore('./data/erp_config.sql');//插入数据
			//清空缓冲
			ob_end_clean();
			return true;
		}
	}
}